package org.aeon.gamechatnest.configuration.security;

import lombok.extern.slf4j.Slf4j;
import org.aeon.gamechatnest.dto.SecurityUserDto;
import org.aeon.gamechatnest.dto.UserCacheDto;
import org.aeon.gamechatnest.pojo.User;
import org.aeon.gamechatnest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 自定义UserDetailsService 用于认证和授权
 * 此处把用户的信息和权限交给spring security
 * spring security会对用户的信息和权限信息进行管理
 *
 * @author hffan
 * serDetailService接口主要定义了一个方法 l
 * oadUserByUsername(String username)用于完成用户信息的查询，
 * 其中username就是登录时的登录名称，登录认证时，需要自定义一个实现类实现UserDetailService接口，
 * 完成数据库查询，该接口返回UserDetail。
 */
@Profile("sec")
@Slf4j
@Component("customerUserDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {
    @Lazy
    @Autowired
    private UserService userService;

    // @Autowired
    // private SysMyPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug(username);
        User user = userService.findByJson(username);
        // 如果用户不存在
        if (user == null) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        SecurityUserDto securityUser = new SecurityUserDto();
        UserCacheDto userCache = new UserCacheDto();
        userCache.setUser(user);
        securityUser.setUserCache(userCache);
        // TODO 授权
        return securityUser;
    }
}
